#!/bin/bash
set -e

# 用法说明
usage() {
    echo "用法: $0 <CubeMX_Project_Dir>"
    echo "例如: $0 ./CubeMXProject"
    exit 1
}

# 检查参数
if [ -z "$1" ]; then
    echo "请指定CubeMX生成的模版库项目目录路径作为参数。"
    usage
fi
CUBEMX_DIR="$1"
if [ ! -d "$CUBEMX_DIR" ]; then
    echo "指定的目录不存在: $CUBEMX_DIR"
    exit 2
fi

# 0. 创建目录
mkdir -p Core Drivers User

# 1. 标准库已在Doc目录下，无需下载

# 2. 拷贝外设标准库驱动
cp -r Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Libraries/STM32F10x_StdPeriph_Driver Drivers/

# 3. 拷贝内核文件
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Libraries/CMSIS/CM3/CoreSupport/core_cm3.c Core/
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/stm32f10x.h Core/
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.h Core/
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/system_stm32f10x.c Core/

# 4. 拷贝启动文件（GCC）
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Libraries/CMSIS/CM3/DeviceSupport/ST/STM32F10x/startup/gcc_ride7/startup_stm32f10x_md.s ./

# 5. 拷贝配置和中断文件
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Project/STM32F10x_StdPeriph_Examples/ADC/3ADCs_DMA/stm32f10x_conf.h User/
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Project/STM32F10x_StdPeriph_Examples/ADC/3ADCs_DMA/stm32f10x_it.c User/
cp Doc/STM32F10x_StdPeriph_Lib_V3.6.0/Project/STM32F10x_StdPeriph_Examples/ADC/3ADCs_DMA/stm32f10x_it.h User/

# 6. 拷贝CubeMX生成的Makefile和链接脚本
if [ -f "$CUBEMX_DIR/Makefile" ]; then
    cp "$CUBEMX_DIR/Makefile" ./
fi
if [ -f "$CUBEMX_DIR/STM32F103XX_FLASH.ld" ]; then
    cp "$CUBEMX_DIR/STM32F103XX_FLASH.ld" ./
fi
# 7. 拷贝CubeMX生成的CMSIS头文件
for f in core_cm3.h cmsis_compiler.h cmsis_gcc.h cmsis_version.h; do
    find "$CUBEMX_DIR" -name $f -exec cp {} Core/ \;
done

# 7. 修改Makefile（用更健壮的awk删除多行变量定义和相关注释块，兼容macOS）


# 8. 修改core_cm3.c中的__STREXH和__STREXB


echo "工程模板自动化配置完成！可直接make编译。" 
